<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>WebSocket</title>
    <script type="text/javascript">

        // 创建websocket实例
        var ws = new WebSocket("ws://localhost:8080/chat");
        /*
         *监听三种状态的变化js会回调
         */
        ws.onopen = function (message) {
            // 连接回调
        };
        ws.onclose = function (message) {
            // 断开连接回调
        };
        ws.onmessage = function (message) {
            // 消息监听
            showMessage(message.data);
        };
        //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
        window.onbeforeunload = function () {
            ws.close();
        };
        //关闭连接
        function closeWebSocket() {
            ws.close();
        }
        //发送消息
        function send() {

            var input = document.getElementById("msg");
            var text = input.value;

            // 消息体JSON 对象 对应JAVA 的 Msg对象
            var data = {
                // 定点发送给其他用户的userId
                toUid: "3d535429-5fcb-4490-bcf7-96fd84bb17b6",
                data: text
            }

            ws.send(JSON.stringify(data));
            input.value = "";
        }
        function showMessage(message) {
            var text = document.createTextNode(JSON.parse(message).data);
            var br = document.createElement("br")
            var div = document.getElementById("showChatMessage");
            div.appendChild(text);
            div.appendChild(br);
        }
    </script>
</head>
<body>
<div>
    style="width: 600px; height: 240px; overflow-y: auto; border: 1px solid #333;"
    id="show">
    <div id="showChatMessage"></div>
    <input type="text" size="80" id="msg" name="msg" placeholder="输入聊天内容"/>
    <input type="button" value="发送" id="sendBn" name="sendBn" onclick="send()">
</div>
</body>
</html>